package com.xww.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


/**
 * @ClassName MyGateWayFilter
 * @Description
 * @Date 2022/1/12 16:42
 **/
@Component
public class MyGateWayFilter implements GlobalFilter, Ordered {

    /**
      * @author xww
      * @description: 全局过滤器 
      * @param: null 
      * @return: 
      * @date: 2022/1/13 11:02
     */ 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            System.out.println("token不能为空");
            return this.getResponseError(exchange,"token不能为空");
        }else {
            if ("ScrmAuthorization".equals(token)){
                return chain.filter(exchange);
            }
            return this.getResponseError(exchange,"无权限");
        }
    }

    /**
      * @author xww
      * @description: 等级
      * @param: null 
      * @return: 
      * @date: 2022/1/13 11:03
     */ 
    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> getResponseError(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject message = new JSONObject();
        message.put("code", -1);
        message.put("message", msg);
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
